package com.szdtoo.service.impl;

import com.szdtoo.dao.RoleDao;
import com.szdtoo.dao.UserDao;
import com.szdtoo.domain.User;
import com.szdtoo.password.PasswordHelper;
import com.szdtoo.service.RoleService;
import com.szdtoo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleService roleService;

    private PasswordHelper passwordHelper;

    @Override
    public User createUser(User user) {
        passwordHelper.encrtyPassword(user);
        return userDao.createUser(user);
    }

    @Override
    public User updateUser(User user) {
        return userDao.updateUser(user);
    }

    @Override
    public void deleteUser(Long userId) {
        userDao.deleteUser(userId);
    }

    /**
     * 修改密码
     * @param userId
     * @param newPassword
     */
    @Override
    public void changePassword(Long userId, String newPassword) {
        User user = userDao.findOne(userId);
        user.setPassword(newPassword);
        passwordHelper.encrtyPassword(user);
        userDao.updateUser(user);
    }

    @Override
    public User findOne(Long userId) {
        return userDao.findOne(userId);
    }

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    /**
     * 根据用户名查找
     * @param username
     * @return
     */
    @Override
    public User findByUsername(String username) {
        return userDao.findByUsername(username);
    }

    /**
     * 根据用户名查找角色
     * @param username
     * @return
     */
    @Override
    public Set<String> findRoles(String username) {
        User user = userDao.findByUsername(username);
        if(user == null) {
            return Collections.emptySet();
        }
        return roleService.findRoles(user.getRoleIds().toArray(new Long[0]));
    }

    @Override
    public Set<String> findPermissions(String username) {
        User user = findByUsername(username);
        if(user == null) {
            return Collections.EMPTY_SET;
        }
        String[] roleIdss = user.getRoleIdsStr().split(",");
        Long[] roleIds = new Long[roleIdss.length];

        for(int i = 0; i < roleIdss.length ; i++){
            roleIds[i] = Long.valueOf(roleIdss[i]);
        }
//        for (String roleId : roleIdss) {
//            long id = new Long(roleId);
//
//        }
//        user.getRoleIds().toArray(new Long[user.getRoleIds().size()]);
        return roleService.findPermissions(roleIds);
    }
}
